AsgDetalleAbono = function(){
	return {
		saveAbono: function(showReport){
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			var jsonString = "";
			Ext.each(Ext.getCmp("asgAbonosCancelarGrid").getStore().getRange(), function(record){
				if(Ext.isEmpty(jsonString)) jsonString = record.data.asgAbonoId; 
				else jsonString += "," + record.data.asgAbonoId;
			});
			jsonString = "[" + jsonString + "]";
			Ext.getCmp("asgDetalleAbonoForm").getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + "/abonos/generatePayment",
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			params: {asgClienteId: AsgSeguros.getAsgClienteId(), jsonString: jsonString},
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						Asg.Grid.loadData("asgAbonosPendientesGrid", action.result.pendientes);
		    			Asg.Grid.loadData("asgAbonosPagadosGrid", action.result.pagos);
		    			Ext.WindowMgr.get("asgDetalleAbonoWindow").hide();
		    			if(showReport && action.result.asgPagoId){
		    				Asg.Window.openWindow("abonos/reciboProvicional", {asgPagoId: action.result.asgPagoId});
		    			}
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		confirmAbono: function(showReport){
			Asg.Message.confirm("\u00BFEst\u00E1 seguro que desea realizar el abono?<br /><b>Total a Cancelar: </b>" + Asg.Utils.getValue("asgPagoTotal"),
				function(btn){
				if(btn == "no") return;
				AsgDetalleAbono.saveAbono(showReport);
			});
		},
		showWindow: function(ctgFormasPago, ctgLugaresPago){
			var records = Ext.getCmp("asgAbonosPendientesGrid").getStore().data.filterBy(function(item){
				return item.data.asgAbonoCancelar == "1" || item.data.asgAbonoCancelar == true;
			}).items;
			if(!records || records.length == 0){
				Asg.Message.alertInvalid("Debe seleccionar al menos un abono a cancelar");
				return;
			}
			var window = Ext.WindowMgr.get("asgDetalleAbonoWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgDetalleAbonoWindow",
				title: Asg.constants.APPLICATION_TITLE,
				modal: true,
				width: 500,
				height: 600,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			Ext.getCmp("asgDetalleAbonoForm").getForm().reset();
	        			var data = new Array();
	        			var total = 0;
	        			Ext.each(Ext.getCmp("asgAbonosPendientesGrid").getStore().getRange(), function(record){
	        				if(record.data.asgAbonoCancelar == "1" || record.data.asgAbonoCancelar == true){
	        					data.push([
        				           record.data.asgAbonoId, 
        				           record.data.asgAbonoNumeroCuota, 
    			        		   record.data.asgAbonoMonto, 
    			        		   record.data.asgAbonoFechaLimite, 
    	        				   record.data.asgPolizaNumero, 
    	        				   record.data.asgClienteId,
    	        				   record.data.asgAbonoCancelar
            				   ]);
    	        			   try{
    	        				   total += parseFloat(record.get("asgAbonoMonto"));
    	        			   }catch(e){}
	        				}
        				});
	        			Asg.Grid.loadData("asgAbonosCancelarGrid", data);
	        			Asg.Utils.setValue("asgPagoTotal", total);
	        		}
	        	},
	        	layout: {
					type: "vbox",
					align : "stretch",
					pack  : "start"
				},
				items: [
			        {
			        	xtype: "form",
			        	id: "asgDetalleAbonoForm",
			        	height: 205,
			        	margins: "5 5 0 5",
			        	bodyPadding: "5 5 5 5",
			        	layout: {
        	        		type: "table",
							columns: 1,
							tableAttrs: {
					            style: {width: "400px"},
					            align: "center"
							}
        	        	},
        	        	defaults: Asg.Form.defaults({width: 375, allowBlank: false}),
        	        	items: [
    	        	        {
    	        	        	xtype: "textfield",
    	        	        	fieldLabel: "No. Referencia",
    	        	        	name: "asgPago.asgPagoNumero",
    	        	        	maxLength: 10,
    	        	        	width: 200
    	        	        },{
    	        	        	xtype: "textfield", 
    	        	        	fieldLabel: "Cobrador",
    	        	        	name: "asgPago.asgPagoCobrador",
    	        	        	maxLength: 120
        	        		},{
	        	        		xtype: "combo",
	        	        		fieldLabel: "Lugar de Pago",
	        	        		name: "asgPago.ctgLugarPago.ctgCatalogoId",
	        	        		store: new Ext.data.SimpleStore({
	        	        			data: ctgLugaresPago || [],
	        	        			fields: ["id", "value"]
	        	        		}),
	        	        		displayField: "value",
	        	        		valueField: "id"
        	        		},{
	        	        		xtype: "combo",
	        	        		fieldLabel: "Forma de Pago",
	        	        		name: "asgPago.ctgFormaPago.ctgCatalogoId",
	        	        		store: new Ext.data.SimpleStore({
	        	        			data: ctgFormasPago || [],
	        	        			fields: ["id", "value"]
	        	        		}),
	        	        		displayField: "value",
	        	        		valueField: "id"
        	        		},{
        	        			xtype: "textarea",
        	        			fieldLabel: "Observaciones",
        	        			name: "asgPago.asgPagoObservacion",
        	        			allowBlank: true,
        	        			height: 50,
        	        			maxLength: 500
        	        		},{
        	        			xtype: "numericfield",
        	        			fieldLabel: "Total a Cancelar",
        	        			id: "asgPagoTotal",
        	        			name: "asgPago.asgPagoTotal",
        	        			readOnly: true,
        	        			labelStyle: "text-align: left !important;",
        	        			maxLength: 10
        	        		}
	        	        ]
			        },{
						xtype: "grid",
						id: "asgAbonosCancelarGrid",
						title: "Cuotas a Cancelar",
						margins: "5 5 5 5",
			        	minHeight: 300,
			        	flex: 1,
						frame: true,
						store: new Ext.data.SimpleStore({
							data: [],
					        fields: [
				                 "asgAbonoId", {name: "asgAbonoNumeroCuota", type: "int"}, "asgAbonoMonto", 
				                 "asgAbonoFechaLimite", "asgPolizaNumero", "asgClienteId",
			      		         "asgAbonoCancelar"
			                ],
			                sorters: [{property: "asgAbonoNumeroCuota", direction: "ASC"}],
			                groupers: [{property: "asgPolizaNumero"}]
						}),
						columns: [
							{header: "#", dataIndex: "asgAbonoNumeroCuota", width: 30},
					        {header: "Valor de la Cuota", dataIndex: "asgAbonoMonto", width: 150, align: "right", renderer: "webMoney"},
					        {header: "Fecha L\u00EDmite de Pago", dataIndex: "asgAbonoFechaLimite", width: 150, align: "right", renderer: "webFormatDateYmd_d_m_Y"},
					        {flex: 1, align: "right"}
					    ],
					    features:[ 
			        		{
				        	   ftype: "grouping",
				        	   enableNoGroups: false,
				        	   groupHeaderTpl: 'No. Poliza: {name}'
				           }
		        		]
					}
		        ],
				buttons: [
		          {
		        	  text: "Realizar Pago",
		        	  handler: function(){
		        		  AsgDetalleAbono.confirmAbono();
		        	  }
		          },{
		        	  text: "Realizar Pago y Mostrar Reporte",
		        	  handler: function(){
		        		  AsgDetalleAbono.confirmAbono(true);
		        	  }
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgDetalleAbonoWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		loadData: function(){
			Asg.Message.progress("Cargando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/abonos/findAllAsgPagos",
  			    params: {
  			    	asgClienteId: AsgSeguros.getAsgClienteId()
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Grid.loadData("asgAbonosPendientesGrid", jsonObject.pendientes);
  			    			Asg.Grid.loadData("asgAbonosPagadosGrid", jsonObject.pagos);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		confirmDeleteAbono: function(){
			var row = Asg.Grid.getSelectedRow("asgAbonosPagadosGrid"); 
			if(!row){
				Asg.Message.alertInvalid("Debe seleccionar el abono a eliminar");
				return;
			}
			Asg.Message.confirmDelete(AsgDetalleAbono.deleteAbono);
		},
		deleteAbono: function(){
			var row = Asg.Grid.getSelectedRow("asgAbonosPagadosGrid");
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			Ext.Ajax.request({
    			timeout: Asg.constants.TIMEOUT_SECONDS,
  			    url: Asg.constants.CONTEXT_PATH + "/abonos/deletePago",
  			    params: {
  			    	asgClienteId: AsgSeguros.getAsgClienteId(),
  			    	asgPagoId: row.get("asgPagoId")
  			    },
  			    callback: function(options, success, response){
  			    	Ext.Msg.hide();
  			    	if(success){
  			    		var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
  			    		if(jsonObject && jsonObject.success){
  			    			Asg.Message.alert(jsonObject.message);
  			    			Asg.Grid.loadData("asgAbonosPendientesGrid", jsonObject.pendientes);
  			    			Asg.Grid.loadData("asgAbonosPagadosGrid", jsonObject.pagos);
  			    		}else{
  			    			Asg.Message.alertInvalid(jsonObject ? (jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE) : Asg.constants.DEFAULT_ERROR_MESSAGE);
  			    		}
  			    	}
  			    }
  			});
		},
		initConfig: function(config){
			config = config || {};
			Ext.define("asgDetallePolizaModel", {
			    extend: "Ext.data.Model",
			    fields: ["asgClienteId", "asgClienteNombreCompleto"]
			});
			var asgDetalleAbonoStore = Ext.create("Ext.data.Store", {
				pageSize: Asg.constants.PAGE_SIZE,
				model: "asgDetallePolizaModel",
				proxy: {
			        type: "ajax",
			        url: Asg.constants.CONTEXT_PATH + "/abonos/doSearch",
			        reader: {
			        	type: "array",
			        	root: "list",
			        	totalProperty: "totalResult"
	        		}
			    },
			    listeners: {
			    	beforeload: function(store, operation, options){
			    		if(!operation) operation = {};
			    		if(!operation.params) operation.params = {};
			    		var form = Ext.getCmp("asgDetalleAbonoForm").getForm();
			    		if(!form.isValid()){
			    			Asg.Message.alertInvalidFields();
			    			return false;
			    		}
			    		var values = form.getValues();
			    		for(value in values){
			    			operation.params["asgSeguroForm." + value] = values[value];
			    		}
			    		if(operation.params.restart){
			    			operation.start = 0;
			    			operation.page = 1;
			    		}
			    		Asg.Grid.loadData("asgAbonosPendientesGrid", []);
		    			Asg.Grid.loadData("asgAbonosPagadosGrid", []);
			    	}
			    	
			    },
			    groupers: [{property: "asgCliente"}]
			});
			return {
				menu: [
	                {
	                	xtype: "buttongroup",
	                	title: "ABONOS",
	                	defaults: {iconAlign: "left"},
	                	padding:"5 5 5 5",
	                	style: "min-width: 200px;",
			            bodyStyle:"min-height:25px",
			            hidden: config.isReadOnly && config.allowDelte,
	                	items: [
            	        	{
            	        		text: "Realizar Pago", 
            	        		iconCls: Asg.constants.ADD_ICON,
            	        		handler:function(){
            	        			AsgDetalleAbono.showWindow(config.ctgFormasPago || [], config.ctgLugaresPago || []);
            	        		}
        	        		},{
        	        			text: "Eliminar Pago",
        	        			iconCls: Asg.constants.DELETE_ICON,
        	        			hidden: !config.allowDelete,
        	        			handler: AsgDetalleAbono.confirmDeleteAbono
    	        			}
	    	            ]
	                },
	                "->",
	                Viewport.getMenuHome()
                ],
				items: {
					border: false,
					bodyStyle: "background: #DFE8F6",
					flex: 1,
					layout: {
						type: "hbox",
						align : "stretch",
						pack  : "start"
					},
					items:[
				        {
				        	width: 500,
				        	border: false,
				        	bodyStyle: "background: #DFE8F6",
				        	layout: {
								type: "vbox",
								align : "stretch",
								pack  : "start"
							},
							items: [
								{
						        	xtype: "form",
						        	id: "asgDetalleAbonoForm",
						        	height: 85,
						        	bodyStyle: "background: #DFE8F6",
						        	layout: "fit",
						        	border: false,
						        	margins: "0 5 5 0",
									items: {
										xtype: "fieldset",
										title: "PARAMETROS DE BUSQUEDA",
										style: "background: #FFFFFF;",
										layout: {
				        	        		type: "table",
											columns: 2,
											tableAttrs: {
									            style: {width: "400px"},
									            align: "center"
											}
				        	        	},
				        	        	defaults: Asg.Form.defaults({width: 250, labelAlign: "top"}),
				        	        	items: [
				    	        	        {
				    	        	        	xtype: "textfield",
				    	        	        	id: "asgPolizaNumero",
				    	        	        	name: "asgPolizaNumero",
				    	        	        	fieldLabel: "No. Poliza",
				    	        	        	width: 100
				    	        	        },{
				    	        	        	xtype: "textfield",
				    	        	        	id: "asgClienteNombreCompleto",
				    	        	        	name: "asgClienteNombreCompleto",
				    	        	        	fieldLabel: "Cliente / Raz\u00F3n Social / Nombre Comercial"
				    	        	        }
					        	        ]
									}
						        },{
									xtype: "grid",
									flex: 1,
									margins: "0 5 0 0",
									frame: true,
									minHeight: 300,
									store: asgDetalleAbonoStore,
									columns: [
				        	           {header: "Cliente", dataIndex: "asgClienteNombreCompleto", minWidth: 200, flex: 1}
			        	            ],
			        	            selModel:{
				        	            listeners: {
				        	            	selectionchange: function(selectionModel, rows){
				        	            		if(rows && rows.length > 0){
				        	            			AsgSeguros.setAsgClienteId(rows[0].get("asgClienteId"));
				        	            			AsgDetalleAbono.loadData();
				        	            		}
				        	            	}
				        	            }
			        	            },
								    dockedItems: [
			                           {
			                        	   xtype: "toolbar",
			                        	   dock: "top",
			                        	   items: [
			                    	           "->",
			                    	           {
			                    	        	   text: "Buscar", 
			                    	        	   iconCls: Asg.constants.SEARCH_ICON,
			                    	        	   handler: function(){
			                    	        		   asgDetalleAbonoStore.currentPage = 1;
			                    	        		   asgDetalleAbonoStore.load({params:{restart: true}});
			                    	        		   AsgSeguros.setAsgClienteId(null);
			                    	        		   AsgSeguros.setAsgPolizaId(null);
			                    	        	   }
			                	        	   },{
			                    	        	   text: "Borrar Filtros", 
			                    	        	   iconCls: Asg.constants.CANCEL_ICON,
			                    	        	   handler: function(){
			                    	        		   Ext.getCmp("asgDetalleAbonoForm").getForm().reset();
			                    	        	   }
			                	        	   }
			                	           ]
			                           },{
			                        	   xtype: "pagingtoolbar",
			                        	   store: asgDetalleAbonoStore,
			                        	   dock: "bottom",
			                        	   displayInfo: true
						               }
			                        ]
								}
					        ]
				        },{
				        	minWidth: 400,
				        	flex: 1,
				        	border: false,
				        	bodyStyle: "background: #DFE8F6",
				        	layout: {
								type: "vbox",
								align : "stretch",
								pack  : "start"
							},
							items: [
								{
									xtype: "grid",
									id: "asgAbonosPendientesGrid",
									title: "Cuotas Pendientes",
									margins: "0 0 5 0",
									flex: 1,
									frame: true,
									minHeight: 250,
									store: new Ext.data.SimpleStore({
										data: [],
								        fields: [
							                 "asgAbonoId", {name: "asgAbonoNumeroCuota", type: "int"}, "asgAbonoMonto", 
							                 "asgAbonoFechaLimite", "asgPolizaNumero", "asgClienteId",
						      		         "asgAbonoCancelar"
						                ],
						                sorters: [{property: "asgAbonoNumeroCuota", direction: "ASC"}],
						                groupers: [{property: "asgPolizaNumero"}]
									}),
									columns: [
								       {
											   xtype:"checkcolumn",
											   align: "center",
											   dataIndex: "asgAbonoCancelar", 
											   width: 30
										},
										{header: "#", dataIndex: "asgAbonoNumeroCuota", width: 30},
								        {header: "Valor de la Cuota", dataIndex: "asgAbonoMonto", width: 150, align: "right", renderer: "webMoney"},
								        {header: "Fecha L\u00EDmite de Pago", dataIndex: "asgAbonoFechaLimite", width: 150, align: "right", renderer: "webFormatDateYmd_d_m_Y"},
								        {flex: 1, align: "right"}
								    ],
								    features:[ 
						        		{
							        	   ftype: "grouping",
							        	   enableNoGroups: false,
							        	   groupHeaderTpl: 'No. Poliza: {name}'
							           }
					        		]
								},{
									xtype: "grid",
									id: "asgAbonosPagadosGrid",
									title: "Cuotas Pagadas",
									margins: "0 0 0 0",
									flex: 1,
									frame: true,
									minHeight: 250,
									store: new Ext.data.SimpleStore({
										data: [],
								        fields: [
								          {name: "asgAbonoNumeroCuota", type: "int"}, "asgAbonoMonto", 
						                  "asgAbonoFechaLimite", "asgPolizaNumero", "asgPagoId",
						                  {
					      		        	name: "asgPagoFecha",
					      		        	convert: function(value){return Asg.Utils.parseDate(value, "d/m/Y H:i:s", "YmdHis");}
					      		          },
					      		          "asgClienteId", "ctgAseguradoraNombre"
						                ],
						                sorters: [
				                          {property: "asgPolizaNumero", direction: "ASC"},
				                          {property: "asgAbonoNumeroCuota", direction: "ASC"}
				                        ],
						                groupers: [{property: "asgPagoFecha"}]
									}),
									columns: [
								        {header: "No. Poliza", dataIndex: "asgPolizaNumero", width: 80},
								        {header: "Aseguradora", dataIndex: "ctgAseguradoraNombre", width: 120},
										{header: "#", dataIndex: "asgAbonoNumeroCuota", width: 30},
								        {header: "Valor de la Cuota", dataIndex: "asgAbonoMonto", width: 150, align: "right", renderer: "webMoney"},
								        {header: "Fecha L\u00EDmite de Pago", dataIndex: "asgAbonoFechaLimite", width: 150, align: "right", renderer: "webFormatDateYmd_d_m_Y"},
								        {flex: 1, align: "right"},
								        {
								        	xtype: "actioncolumn",
								        	width: 34,
								        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/page_pdf.png",
								        	iconCls: "icon",
								        	handler: function(grid, rowIndex, colIndex) {
							                    var record = grid.getStore().getAt(rowIndex);
							                    if(record){
							                    	Asg.Window.openWindow("abonos/reciboProvicional", {asgPagoId: record.get("asgPagoId")});
							                    }
							                }
								        }
								    ],
								    features:[ 
						        		{
							        	   ftype: "grouping",
							        	   enableNoGroups: false,
							        	   groupHeaderTpl: 'Abonos realizados el {name}'
							           }
					        		]
								}
					        ]
				        }
			        ]
				}
			};
		}
	};
}();